package com.gitee.flow.util;

import com.gitee.jmash.core.orm.DtoPageImpl;
import com.gitee.jmash.core.orm.DtoTotal;
import org.flowable.common.engine.api.query.Query;

public class FlowablePageUtil {

  /** 翻页查询. */
  public static <T extends Query<?, ?>, U> DtoPageImpl<U, DtoTotal> listPage(int curPage,
      int pageSize, Query<T, U> query) {
    curPage = curPage < 1 ? 1 : curPage;
    pageSize = pageSize < 1 ? 10 : pageSize;
    int totalSize = (int) query.count();
    // 加入判断
    if (totalSize != 0) {
      // 调整页码
      int pageCount = (totalSize / pageSize) + ((totalSize % pageSize) == 0 ? 0 : 1);
      curPage = curPage > pageCount ? pageCount : curPage;
    }
    int firstResult = (curPage - 1) * pageSize;
    DtoTotal total = new DtoTotal();
    total.setTotalSize(totalSize);
    return new DtoPageImpl<>(query.listPage(firstResult, pageSize), curPage, pageSize, total);
  }

}
